﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using edowork.com.SQL2005;


namespace WebInvoicingsys.system.purchase
{
    public partial class purchasecheck_check : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "", Total_qty = "0", Total_in_price = "0", Total_in_money = "0";

        //传入的参数
        string id, start_date, end_date, supplier, pcsid;


        /// <summary>
        /// 取得传入的参数
        /// </summary>
        /// <returns></returns>
        private bool GetParma()
        {
            try
            {
                id = Request.Params["id"].ToString();
                start_date = Request.Params["start_date"].ToString();
                end_date = Request.Params["end_date"].ToString();
                supplier = Request.Params["supplier"].ToString();
                pcsid = Request.Params["pcsid"].ToString();
            }
            catch
            {
                //显示出错信息
                alert_msg = String.Format(Scripts.alert_warning, Errormsg.er_Parampost);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 绑定单据主信息
        /// </summary>
        /// <returns></returns>
        private void BindInfo()
        {
            string error_msg = "";

            //构造SQL语句
            string sql = @"select  a.pspid, 
                                   (select years from purchaseplan where a.pspid=purchaseplan.pspid) years,
                                   (select month from purchaseplan where a.pspid=purchaseplan.pspid) months,
                                   a.pcsid, 
                                   a.billdate, 
                                   a.arrivaldate, 
                                   (select suppliername from supplier where a.supplierid=supplier.supplierid) suppliername,
                                   a.phone,
                                   a.fax,
                                   (select settlename from settle where a.settleid=settle.settleid) settlename,
                                   a.period,
                                   (select username from sysuser where a.userid=sysuser.userid) username,
                                   a.remark,
                                   a.checkstu,
                                   (select username from sysuser where a.checkuserid=sysuser.userid) checkusername,
                                   a.checkdate,
                                   a.checkremark,
                                   a.sysdate
                                from purchase a
                                  where a.pcsid='{0}'";

            sql = String.Format(sql, id);

            Execute exec = new Execute(Session["connectionString"].ToString());

            DataSet ds = exec.ExecSQLQueryDataSet(sql, ref error_msg);

            if (ds == null)
            {
                //显示出错信息
                alert_msg = String.Format(Scripts.alert_warning, error_msg);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                txt_pspid.Text = dr["pspid"].ToString();
                txt_billdate.Text = dr["billdate"].ToString();
                txt_arrivaldate.Text = dr["arrivaldate"].ToString();
                txt_suppliername.Text = dr["suppliername"].ToString();
                txt_phone.Text = dr["phone"].ToString();
                txt_fax.Text = dr["fax"].ToString();
                txt_settlename.Text = dr["settlename"].ToString();
                txt_period.Text = dr["period"].ToString();
                txt_username.Text = dr["username"].ToString();
                txt_sysdate.Text = dr["sysdate"].ToString();
                txt_remark.Text = dr["remark"].ToString();

                txt_checkremark.Text = dr["checkremark"].ToString();
            }
        }
        
        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty");
            dtList.Columns.Add("in_price");
            dtList.Columns.Add("in_money");
            dtList.Columns.Add("remark");

            DataTable dtData = ((purchase_product_class)Session["purchase_product"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty"] = dr["qty"].ToString();
                drnew["in_price"] = dr["in_price"].ToString();
                drnew["in_money"] = dr["in_money"].ToString();
                drnew["remark"] = dr["remark"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParma();

                try
                {
                    ((purchase_product_class)Session["purchase_product"]).Reset();
                }
                catch
                {
                    Session.Add("purchase_product", new purchase_product_class(Session["connectionString"].ToString()));
                }
                finally
                {
                    ((purchase_product_class)Session["purchase_product"]).getDataList(id);
                }

                BindInfo();

                Bind();

                Total_qty = ((purchase_product_class)Session["purchase_product"]).Total_qty.ToString();
                Total_in_price = ((purchase_product_class)Session["purchase_product"]).Total_in_price.ToString();
                Total_in_money = ((purchase_product_class)Session["purchase_product"]).Total_in_money.ToString();
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (GetParma() == false)
            {
                return;
            }

            alert_msg = "";
            
            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;
              
                //更新主表的审批备注
                sql = "update purchase set checkremark='{1}' where pcsid='{0}' and checkstu='0' and m_stu='0' and b_open='0'";

                sql = String.Format(sql, id, txt_checkremark.Text.Trim());

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "采购备注保存失败，错误原因：采购单的状态已变化。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }


                tran.Commit();
                tranutil.CloseConnection();
            }

            Bind();

            Total_qty = ((purchase_product_class)Session["purchase_product"]).Total_qty.ToString();
            Total_in_price = ((purchase_product_class)Session["purchase_product"]).Total_in_price.ToString();
            Total_in_money = ((purchase_product_class)Session["purchase_product"]).Total_in_money.ToString();

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }
        
        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            GetParma();

            string url = "/system/purchase/purchasecheck_list.aspx?start_date={0}&end_date={1}&supplier={2}&pcsid={3}";

            url = String.Format(url, start_date, end_date, supplier, pcsid);

            Response.Redirect(url);
        }

        //审核
        protected void btnCheck_Click(object sender, EventArgs e)
        {
            if (GetParma() == false)
            {
                return;
            }

            alert_msg = "";

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;
                DataSet dsResult = null;

                //检查当前选择的年份与月份是否在结算日期之前
                sql = String.Format("select * from (select isnull(max(years+months), '') dates from sys_monthly_main) a where a.dates >='{0}{1}'", DateTime.Parse(txt_billdate.Text.Trim()).ToString("yyyy"), DateTime.Parse(txt_billdate.Text.Trim()).ToString("MM"));

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前选择的月份在结算日期之后。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //更新主表的审批信息
                sql = "update purchase set checkuserid='{1}', checkdate='{2}', checkstu='1', checkremark='{3}' where pcsid='{0}' and checkstu='0' and m_stu='0' and b_open='0'";

                sql = String.Format(sql, id, Session["userid"].ToString(), DateTime.Now.ToString("yyyy-MM-dd"), txt_checkremark.Text.Trim());

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "采购单审批失败，错误原因：采购单的状态已变化。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }


                tran.Commit();
                tranutil.CloseConnection();
            }

            Bind();

            Total_qty = ((purchase_product_class)Session["purchase_product"]).Total_qty.ToString();
            Total_in_price = ((purchase_product_class)Session["purchase_product"]).Total_in_price.ToString();
            Total_in_money = ((purchase_product_class)Session["purchase_product"]).Total_in_money.ToString();

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }
    }
}